/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tang.springcloudvv.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.tang.springcloudvv.gateway.service.DiscoveryClientService;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @author tangfuzhong.
 * @Time 2022年4月07日
 * @Version 1.0
 */
@Component
public class WebservicePreFilter extends ZuulFilter {

	@Autowired
	private DiscoveryClientService discoveryClientService;

    protected static final Logger logger = LoggerFactory.getLogger(WebservicePreFilter.class);
    
    /**
     * 过滤类型
     *pre：路由之前
     *routing：路由之时
     *post： 路由之后
     *error：发送错误调用
     * @return String
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    
    @Override
    public int filterOrder() {
        return 1;
    }
    
    /*
    *是否需要过滤
    */
    @Override
    public boolean shouldFilter() {
    	RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse response = ctx.getResponse(); 
        if (1==2)
        {
        	return false;
        }
    	return true;
    }
    
    /*
    *过滤规则
    */
    @Override
    public Object run() {
        
        logger.info("====gateway=UserSession=PreFilter=====");
		discoveryClientService.getServerList();
        
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();     
        dealToken(request);
        return null;
    }

	private void dealToken(HttpServletRequest request) {
		try {

		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		
	}

    private void reWriteRequest(RequestContext ctx,HttpServletRequest request) {
		try {
			InputStream in = request.getInputStream();
			String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
			JSONObject jsonObject = null;
			if (StringUtils.isEmpty(body))
			{
				jsonObject = new JSONObject();
			}
			else
			{				
				jsonObject = JSONObject.parseObject(body);
			}

			/* 重写body内容
			 * 但是接收的controller的方法必须用RequestBody接收这个body内容
			 * 要求所有controller的方法都加上参数@RequestBody String body，改造很大：
			   public Object firstLoginXuanfangAct(@RequestBody String body,HttpServletRequest request,HttpServletResponse response)
			 */
			String newBody = jsonObject.toString();
			final byte[] reqBodyBytes = newBody.getBytes();
			ctx.setRequest(new HttpServletRequestWrapper(request) {
				@Override
				public ServletInputStream getInputStream() throws IOException {
					return new ServletInputStreamWrapper(reqBodyBytes);
				}

				@Override
				public int getContentLength() {
					return reqBodyBytes.length;
				}

				@Override
				public long getContentLengthLong() {
					return reqBodyBytes.length;
				}
			});
		} catch (IOException e) {
			logger.error("UserSessionPreFilter Err:",e);
		}
	}
}
